<script setup lang="ts">
import type { Ref } from "vue";
import { ref, onMounted, reactive, toRefs, computed } from "vue";
import { findPage, deleteUser, updateUser } from "@/api/user";
import depositApi from "@/api/deposit";
import dictApi from "@/api/dictionary";
import { cloneDeep, debounce } from "@pureadmin/utils";
import { useRouter } from "vue-router";
import {
  PlusColumn,
  PageInfo,
  ButtonsCallBackParams,
  useTable,
  PlusPageInstance,
  PlusDialog,
  PlusDialogForm,
  OptionsRow
} from "plus-pro-components";
import { useSelect } from "@/utils/useSelect";
import { message } from "@/utils/message";
import { ElMessage, ElMessageBox, FormRules } from "element-plus";
const router = useRouter();

const { usersStatusList, usersDepositList } = useSelect();
const { buttons } = useTable();
defineOptions({
  name: "userList"
});

// 用户状态
const userStatusList: Ref<OptionsRow[]> = ref([]);

const getOptions = async () => {
  const user_status = await dictApi.dictionaryDataAll({
    code: "user_status"
  });
  userStatusList.value = user_status.data;
};

getOptions();

const plusPageInstance = ref<PlusPageInstance | null>(null);
const moneyTabconfig: PlusColumn[] = [
  {
    label: "用户当前余额",
    prop: "userMoney",
    fieldProps: {
      disabled: true,
      readonly: true
    }
  },
  {
    label: "充值金额",
    prop: "money",
    valueType: "input-number",
    fieldProps: {
      type: "number",
      min: 0.1
    }
  },
  {
    label: "充值方式",
    prop: "type",
    valueType: "select",
    options: async () => {
      return [];
    }
  },
  {
    label: "备注",
    prop: "description",
    valueType: "textarea"
  }
];
const tableConfig: PlusColumn[] = [
  {
    label: "ID",
    prop: "id",
    hideInSearch: true,
    hideInForm: true
  },
  {
    label: "用户名",
    prop: "username"
    // fieldProps: computed(() => ({ disabled: currentRow.value.username })),
  },
  {
    label: "真实姓名",
    prop: "realName"
  },
  {
    label: "手机号",
    prop: "phone"
  },
  {
    label: "状态",
    prop: "status",
    valueType: "select",
    options: computed(() => userStatusList.value)
  },
  {
    label: "等级",
    prop: "level",
    hideInSearch: true,
    minWidth: 40
  },
  {
    label: "生日",
    prop: "birthday",
    valueType: "date-picker",
    hideInSearch: true,
    fieldProps: {
      valueFormat: "YYYY-MM-DD"
    }
  },
  {
    label: "钱包额度",
    prop: "money",
    valueType: "input-number",
    hideInSearch: true,
    hideInForm: true,
    fieldProps: {
      min: 0.0
    }
  },
  {
    label: "用户唯一标识",
    prop: "uniqueToken",
    hideInSearch: true,
    hideInForm: true,
    tableColumnProps: {
      showOverflowTooltip: true
    }
  },
  {
    label: "注册时间",
    prop: "createTime",
    valueType: "date-picker",
    hideInSearch: true,
    hideInForm: true
  }
];

buttons.value = [
  {
    text: "编辑",
    code: "update",
    props: {
      type: "success"
    }
  },
  {
    text: "删除",
    code: "delete",
    confirm: true,
    props: { type: "warning" }
  },
  {
    text: "查看",
    code: "view",
    props: {
      type: "primary"
    }
  },
  {
    text: "充值",
    code: "money"
  }
];

interface State {
  /**
   * 检索数据
   */
  query?: any;
  /**
   * 当前选择的行数据
   */
  currentRow: any;

  /**
   * 表单弹窗是否可见
   */
  visible: boolean;

  /**
   * 充值是否可见
   */
  moneyVisible: boolean;
  /**
   * 详情弹窗是否可见
   */
  detailsVisible: boolean;
  /**
   * 当前选择多行的id集合
   */
  selectedIds: number[];
  /**
   *  提交loading
   */
  confirmLoading: boolean;
  /**
   * 是否是创建
   */
  isCreate: boolean;
  /**
   * 是否批量
   */
  isBatch: boolean;
  /**
   * 表单
   */
  form: {
    username: string;
  };
  moneyForm: {
    userMoney: number;
    money: number;
    description: string;
    type: string;
    userId: number;
  };
  /**
   * 校验
   */
  rules?: FormRules;
  /**
   * 充值校验
   */
  moneyRules: FormRules;
}

const state = reactive<State>({
  query: {},
  currentRow: {},
  visible: false,
  detailsVisible: false,
  confirmLoading: false,
  moneyVisible: false,
  isCreate: true,
  isBatch: false,
  selectedIds: [],
  form: {
    username: ""
  },
  moneyForm: {
    money: 0,
    userMoney: 0,
    description: "",
    type: "",
    userId: null
  },
  moneyRules: {
    money: {
      required: true
    }
  },
  rules: {}
});
const dialogTitle = computed(() => (state.isCreate ? "新增" : "编辑"));
function handleBeforeSearch(values: any) {
  const params = cloneDeep(values);
  return params;
}

// 按钮操作
const handleTableOption = ({ row, buttonRow }: ButtonsCallBackParams): void => {
  state.currentRow = { ...row };
  switch (buttonRow.code) {
    case "update":
      state.form = { ...row } as any;
      state.isCreate = false;
      state.visible = true;
      break;
    case "delete":
      state.isBatch = false;
      handleDelete();
      break;
    case "view":
      state.detailsVisible = true;
      break;
    case "money":
      const { money: userMoney } = row;
      state.moneyForm = {
        money: null,
        userMoney,
        description: "",
        type: "admin",
        userId: row.id
      };
      state.moneyVisible = true;
      break;
  }
};

// 删除
const handleDelete = async (): Promise<void> => {
  try {
    const params = state.isBatch
      ? state.selectedIds
      : [state.currentRow.id as number];
    await deleteUser({ ids: params });
    message("操作成功", { type: "success" });
    refresh();
  } catch (error) {}
};

// 批量删除
const handleBatchDelete = async () => {
  if (!state.selectedIds.length) {
    message("请选择数据！", { type: "warning" });
    return;
  }
  try {
    await ElMessageBox.confirm("确定删除所选数据", "提示");
    state.isBatch = true;
    handleDelete();
  } catch (error) {
    console.log(error);
  }
};

// 选择
const handleSelect = (data: any) => {
  state.selectedIds = [...data].map(item => item.id);
};

// 取消
const handleCancel = () => {
  state.visible = false;
};

// 提交表单成功
const handleSubmit = async () => {
  try {
    state.confirmLoading = true;
    const params = { ...state.form };
    if (state.isCreate) {
      ElMessage.success("创建成功");
    } else {
      // await GroupServe.update(params);
      console.log(params);
      await updateUser(params);
      ElMessage.success("更新成功");
    }
    handleCancel();
    refresh();
  } catch (error) {}
  state.confirmLoading = false;
};

//充值表单提
const moneyConfigClick = async () => {
  try {
    state.confirmLoading = true;
    await depositApi.deposit(state.moneyForm).then(res => {
      ElMessage.success("操作成功");
      state.moneyVisible = false;
    });
  } catch (error) {}
  state.confirmLoading = false;
};
const moneyCancel = async () => {
  state.moneyVisible = false;
};

function refresh() {
  plusPageInstance.value.getList();
}

const getList = async (query: PageInfo) => {
  const result = await findPage(Object.assign({}, query));
  return { data: result.data.list, total: result.data.total };
};

const {
  form,
  moneyRules,
  confirmLoading,
  rules,
  currentRow,
  visible,
  detailsVisible,
  moneyVisible,
  moneyForm
} = toRefs(state);
</script>

<template>
  <el-card shadow="never">
    <PlusPage
      ref="plusPageInstance"
      :columns="tableConfig"
      :request="getList"
      :is-card="false"
      :before-search-submit="handleBeforeSearch"
      :pagination="{
        background: true
      }"
      :table="{
        actionBar: {
          buttons,
          showNumber: 3
        },
        onClickAction: handleTableOption,
        isSelection: true,
        onSelectionChange: handleSelect
      }"
      :search="{
        showNumber: 3
      }"
    >
      <template #table-title>
        <el-button
          size="small"
          type="primary"
          @click="router.push({ name: 'userAdd' })"
        >
          <IconifyIconOnline icon="ep:plus" class="mr-1" />
          新增用户
        </el-button>
        <el-button size="small" type="danger" @click="handleBatchDelete">
          <IconifyIconOnline icon="ep:delete" class="mr-1" />
          删除用户
        </el-button>
      </template>
    </PlusPage>

    <!-- 查看弹窗 -->
    <PlusDialog
      v-model="detailsVisible"
      title="用户详情"
      top="26vh"
      :has-footer="false"
    >
      <PlusDescriptions :column="2" :columns="tableConfig" :data="currentRow" />
    </PlusDialog>

    <!-- 弹窗编辑 -->
    <PlusDialogForm
      v-model:visible="visible"
      v-model="form"
      :form="{ columns: tableConfig, labelPosition: 'top', rules }"
      :dialog="{
        title: dialogTitle + '用户组',
        width: '540px',
        top: '18vh',
        confirmLoading
      }"
      @confirm="handleSubmit"
      @cancel="handleCancel"
    >
      <template #plus-field-username>
        <el-input v-model="form.username" disabled readonly />
      </template>
    </PlusDialogForm>

    <!-- 打开充值窗口 -->
    <PlusDialogForm
      v-model:visible="moneyVisible"
      v-model="moneyForm"
      :form="{
        columns: moneyTabconfig,
        labelPosition: 'top',
        rules: moneyRules
      }"
      :dialog="{
        title: '充值',
        width: '540px',
        top: '18vh',
        confirmLoading
      }"
      @confirm="moneyConfigClick"
      @cancel="moneyCancel"
    />
  </el-card>
</template>
